package com.wondertek.web.controller.business;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wondertek.common.base.Result;
import com.wondertek.common.exception.AppException;
import com.wondertek.common.log.AutoLogUtil;
import com.wondertek.common.util.security.PreAuthorize;
import com.wondertek.service.dto.business.req.AccessoryAddReq;
import com.wondertek.service.dto.business.req.AccessoryBindIpcPeq;
import com.wondertek.service.dto.business.req.AccessoryPageReq;
import com.wondertek.service.dto.business.res.AccessoryPageRes;
import com.wondertek.service.dto.business.res.SiteDeviceAccessoryRes;
import com.wondertek.service.dto.sys.req.BaseUpdateReq;
import com.wondertek.service.entity.business.AccessoryPo;
import com.wondertek.service.entity.business.IpcAccessoryPo;
import com.wondertek.service.entity.business.RoomPo;
import com.wondertek.service.sdk.iotdh.dto.req.DeleteAccessoryReq;
import com.wondertek.service.sdk.iotdh.dto.req.SetAccessoryAreaReq;
import com.wondertek.service.sdk.iotdh.dto.req.SetAccessoryPairReq;
import com.wondertek.service.sdk.iotdh.dto.req.SetSmokeAccessoryInfoReq;
import com.wondertek.service.sdk.iotdh.dto.res.GetAccessoryInfoRes;
import com.wondertek.service.sdk.iotdh.dto.res.alarmBell.SetODAlarmBellAccessoryInfoReq;
import com.wondertek.service.sdk.iotdh.dto.res.doorDetector.SetDoorDetectorAccessoryInfoReq;
import com.wondertek.service.sdk.iotdh.dto.res.doorDetectorPlus.SetDoorDetectorPlusAccessoryInfoReq;
import com.wondertek.service.sdk.iotdh.dto.res.keyboard.SetKeyboardAccessoryInfoReq;
import com.wondertek.service.sdk.iotdh.dto.res.pir.SetPIRAccessoryInfoReq;
import com.wondertek.service.sdk.iotdh.service.DhDeviceService;
import com.wondertek.service.service.business.AccessoryService;
import com.wondertek.service.service.business.DeviceService;
import com.wondertek.service.service.business.IpcAccessoryService;
import com.wondertek.service.service.business.RoomService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author wangyu
 */
@RestController
@RequestMapping("/backend/business/accessory/")
@Tag(name = "配件管理")
public class AccessoryController {

    @Autowired
    private AccessoryService accessoryService;

    @Resource
    private RoomService roomService;

    @Resource
    private DhDeviceService dhDeviceService;

    @Resource
    private DeviceService deviceService;

    @Resource
    private IpcAccessoryService ipcAccessoryService;

    @PostMapping("/getStreamUrlByAccessory")
    @Operation(summary = "配件获取视频")
    public Result getStreamUrlByAccessory(@RequestParam("businessType") String businessType,
                                          @RequestParam("snCode") String snCode,
                                                  @RequestParam("startTime") String startTime,
                                                  @RequestParam("endTime") String endTime){
        Result result = new Result<>();
        result.setData(ipcAccessoryService.getStreamUrlByAccessory(snCode,startTime,endTime,businessType));
        return result;
    }

    @PostMapping("/bindIpc")
    @Operation(summary = "配件绑定ipc")
    public Result bindIpc(@RequestBody AccessoryBindIpcPeq req){
        //先查询是否已经绑定
        LambdaQueryWrapper<IpcAccessoryPo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(IpcAccessoryPo::getAccessoryId,req.getAccessoryId());
        lambdaQueryWrapper.eq(IpcAccessoryPo::getIpcId,req.getIpcId());
        long count = ipcAccessoryService.count(lambdaQueryWrapper);
        if(count>0){
            throw new AppException("ipc.is.bind");
        }
        IpcAccessoryPo ipcAccessoryPo = new IpcAccessoryPo();
        BeanUtil.copyProperties(req,ipcAccessoryPo);
        ipcAccessoryPo.setIsDelete(0);
        ipcAccessoryService.save(ipcAccessoryPo);
        return Result.success();
    }

    @PostMapping("/cancelBindIpc")
    @Operation(summary = "取消配件绑定ipc")
    public Result cancelBindIpc(@RequestBody BaseUpdateReq req){
        ipcAccessoryService.removeById(req.getId());
        return Result.success();
    }

    @PostMapping("/getBindInfo")
    @Operation(summary = "获取绑定信息")
    public Result<List<IpcAccessoryPo>> getBindInfo(@RequestParam("accessoryId") String accessoryId){
        LambdaQueryWrapper<IpcAccessoryPo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(IpcAccessoryPo::getAccessoryId,accessoryId);
        List<IpcAccessoryPo> list = ipcAccessoryService.list(lambdaQueryWrapper);
        return Result.success(list);
    }

    @PostMapping("/findAccessoryPage")
    @Operation(summary = "web分页查询配件")
    @PreAuthorize("@el.check('backend:business:accessory:findAccessoryPage')")
    public Result<Page<AccessoryPageRes>> findAccessoryPage(@RequestBody AccessoryPageReq req){

        return Result.success(accessoryService.webPage(req));
    }

    @PostMapping("/addAccessory")
    @Operation(summary = "新增配件")
    @PreAuthorize("@el.check('backend:business:accessory:addAccessory')")
    public Result addAccessory(@RequestBody @Validated AccessoryAddReq req){
        accessoryService.addAccessory(req);
        return Result.success();
    }

    @PostMapping("/updAccessory")
    @Operation(summary = "修改配件")
    @PreAuthorize("@el.check('backend:business:accessory:updAccessory')")
    public Result updAccessory(@RequestBody @Validated SetAccessoryAreaReq req){
        accessoryService.updAccessory(req);
        return Result.success();
    }

    @PostMapping("/delAccessory")
    @Operation(summary = "删除配件")
    @PreAuthorize("@el.check('backend:business:accessory:delAccessory')")
    public Result delAccessory(@RequestBody DeleteAccessoryReq req){
        accessoryService.delAccessory(req);
        return Result.success();
    }

    @PostMapping("/detail")
    @Operation(summary = "详情")
    @PreAuthorize("@el.check('backend:business:accessory:detail')")
    public Result<GetAccessoryInfoRes> detail(@RequestBody @Validated BaseUpdateReq req){
        return accessoryService.detail(req.getId());
    }

    @PostMapping("/set")
    @Operation(summary = "烟感开关设置")
    @PreAuthorize("@el.check('backend:business:accessory:set')")
    public Result<?> setSmokeAccessoryInfo(@RequestBody @Validated SetSmokeAccessoryInfoReq req) {
        AccessoryPo accessoryPo = new AccessoryPo();
        accessoryPo.setAccessoryCode(req.getAccessoryInfos().get(0).getId());
        SiteDeviceAccessoryRes res = deviceService.selectSiteDeviceAccessory(accessoryPo);
        AutoLogUtil.save("sys","log.smoke.switch.set","烟感sn码:"+res.getAccessorySn(),
                res.getSiteName(),res.getDeviceSn(),res.getSiteId(),res.getAccessorySn());
        return dhDeviceService.setSmokeAccessoryInfo(req);
    }

    @PostMapping("/keyboard/set")
    @Operation(summary = "无线键盘开关设置")
    @PreAuthorize("@el.check('backend:business:accessory:keyboard:set')")
    public Result<?> setSmokeAccessoryInfo(@RequestBody @Validated SetKeyboardAccessoryInfoReq req) {
        AccessoryPo accessoryPo = new AccessoryPo();
        accessoryPo.setAccessoryCode(req.getAccessoryInfos().get(0).getId());
        SiteDeviceAccessoryRes res = deviceService.selectSiteDeviceAccessory(accessoryPo);
        AutoLogUtil.save("sys","log.keyboard.switch.set","无线键盘sn码:"+res.getAccessorySn(),
                res.getSiteName(),res.getDeviceSn(),res.getSiteId(),res.getAccessorySn());
        return dhDeviceService.setKeyboardAccessoryInfo(req);
    }

    @PostMapping("/setODAlarmBellAccessoryInfo")
    @Operation(summary = "设置室外警号")
    @PreAuthorize("@el.check('backend:business:accessory:setODAlarmBellAccessoryInfo')")
    public Result<?> setODAlarmBellAccessoryInfo(@RequestBody @Validated SetODAlarmBellAccessoryInfoReq req) {
        AccessoryPo accessoryPo = new AccessoryPo();
        accessoryPo.setAccessoryCode(req.getAccessoryInfos().get(0).getId());
        SiteDeviceAccessoryRes res = deviceService.selectSiteDeviceAccessory(accessoryPo);
        AutoLogUtil.save("sys","log.outdoor.set","室外警号sn码:"+res.getAccessorySn(),
                res.getSiteName(),res.getDeviceSn(),res.getSiteId(),res.getAccessorySn());
        return dhDeviceService.setODAlarmBellAccessoryInfo(req);
    }

    @PostMapping("/setDoorDetectorAccessoryInfo")
    @Operation(summary = "设置⻔磁信息")
    @PreAuthorize("@el.check('backend:business:accessory:setDoorDetectorAccessoryInfo')")
    public Result<?> setDoorDetectorAccessoryInfo(@RequestBody @Validated SetDoorDetectorAccessoryInfoReq req) {
        //校验分区是否撤防
        this.isArm(req.getAccessoryInfos().get(0).getId());
        AccessoryPo accessoryPo = new AccessoryPo();
        accessoryPo.setAccessoryCode(req.getAccessoryInfos().get(0).getId());
        SiteDeviceAccessoryRes res = deviceService.selectSiteDeviceAccessory(accessoryPo);
        AutoLogUtil.save("sys","log.door.magnetic.set","⻔磁sn码:"+res.getAccessorySn(),
                res.getSiteName(),res.getDeviceSn(),res.getSiteId(),res.getAccessorySn());
        accessoryService.setDoorDetectorAccessoryInfo(req);
        return Result.success();
    }

    private void isArm(String accCode){
        LambdaQueryWrapper<AccessoryPo> accessoryPoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        accessoryPoLambdaQueryWrapper.eq(AccessoryPo::getAccessoryCode,accCode);
        List<AccessoryPo> list = accessoryService.list(accessoryPoLambdaQueryWrapper);
        if(CollectionUtils.isNotEmpty(list)){
            //根据roomid查布防模式
            AccessoryPo accessory = list.get(0);
            LambdaQueryWrapper<RoomPo> roomPoLambdaQueryWrapper = new LambdaQueryWrapper<>();
            roomPoLambdaQueryWrapper.eq(RoomPo::getId,accessory.getRoomId());
            List<RoomPo> list1 = roomService.list(roomPoLambdaQueryWrapper);
            if (CollectionUtils.isNotEmpty(list1)){
                RoomPo roomPo = list1.get(0);
                if (!"D".equals(roomPo.getMode())){
                    throw new AppException("this.room.not.withdraw");
                }
            }
        }
    }

    @PostMapping("/setDoorDetectorPlusAccessoryInfo")
    @Operation(summary = "设置升级⻔磁信息")
    @PreAuthorize("@el.check('backend:business:accessory:setDoorDetectorPlusAccessoryInfo')")
    public Result<?> setDoorDetectorPlusAccessoryInfo(@RequestBody @Validated SetDoorDetectorPlusAccessoryInfoReq req) {
        //校验分区是否撤防
        this.isArm(req.getAccessoryInfos().get(0).getId());
        AccessoryPo accessoryPo = new AccessoryPo();
        accessoryPo.setAccessoryCode(req.getAccessoryInfos().get(0).getId());
        SiteDeviceAccessoryRes res = deviceService.selectSiteDeviceAccessory(accessoryPo);
        AutoLogUtil.save("sys","log.upgrade.door.magnetic.set","升级⻔磁sn码:"+res.getAccessorySn(),
                res.getSiteName(),res.getDeviceSn(),res.getSiteId(),res.getAccessorySn());
        accessoryService.setDoorDetectorPlusAccessoryInfo(req);
        return Result.success();
    }

    @PostMapping("/setPIRAccessoryInfo")
    @Operation(summary = "设置PIR相机信息")
    @PreAuthorize("@el.check('backend:business:accessory:setPIRAccessoryInfo')")
    public Result<?> setPIRAccessoryInfo(@RequestBody @Validated SetPIRAccessoryInfoReq req) {
        //校验分区是否撤防
        this.isArm(req.getAccessoryInfos().get(0).getId());
        AccessoryPo accessoryPo = new AccessoryPo();
        accessoryPo.setAccessoryCode(req.getAccessoryInfos().get(0).getId());
        SiteDeviceAccessoryRes res = deviceService.selectSiteDeviceAccessory(accessoryPo);
        AutoLogUtil.save("sys","log.pir.set","PIR相机sn码:"+res.getAccessorySn(),
                res.getSiteName(),res.getDeviceSn(),res.getSiteId(),res.getAccessorySn());
        accessoryService.setPIRAccessoryInfo(req);
        return Result.success();
    }

    @PostMapping("/setAccessoryPair")
    @Operation(summary = "挂载配件")
    @PreAuthorize("@el.check('backend:business:accessory:setAccessoryPair')")
    public Result setAreaArmMode(@RequestBody @Validated SetAccessoryPairReq req) {
        accessoryService.setAccessoryPair(req);
        return Result.success();
    }


}

